package com.example.demo.user.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.user.entity.User;
import com.example.demo.user.mapper.UserMapper;
import com.example.demo.user.service.UserService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @ClassName UserServiceImpl
 * @Description 用户服务实现类
 * @Author System
 * @Date 2025/9/25
 **/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    
    private static final Log log = LogFactory.get();
    
    @Override
    public User getUserByUsername(String username) {
        return baseMapper.selectByUsername(username);
    }
    
    @Override
    public User validateUser(String username, String password) {
        try {
            // 1. 根据用户名查询用户
            User user = getUserByUsername(username);
            if (user == null) {
                log.warn("用户不存在: {}", username);
                return null;
            }
            
            // 2. 验证密码
            if (BCrypt.checkpw(password, user.getPassword())) {
                log.info("用户登录验证成功: {}", username);
                // 3. 更新最后登录时间
                updateLastLoginTime(user.getId());
                return user;
            } else {
                log.warn("用户密码错误: {}", username);
                return null;
            }
            
        } catch (Exception e) {
            log.error("用户登录验证异常: {}", e.getMessage(), e);
            return null;
        }
    }
    
    @Override
    public void updateLastLoginTime(Long userId) {
        try {
            User user = new User();
            user.setId(userId);
            user.setLastLoginTime(LocalDateTime.now());
            baseMapper.updateById(user);
        } catch (Exception e) {
            log.error("更新用户最后登录时间失败: {}", e.getMessage(), e);
        }
    }
}
